package cn.enjoy.tool.juc.DataBaseConnect;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * 数据库连接池-超时连接
 *
 * @author K
 * @date 2021/7/29 下午3:35
 */
public class ConnectionPool {

    private final LinkedList<Connection> pool = new LinkedList<>();

    ConnectionPool(int size) {
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                pool.add(ConnectionDriver.createConnection());
            }
        }
    }

    public void releaseConnection(Connection connection) {
        if (connection != null) {
            synchronized (pool) {
                pool.addLast(connection);
                pool.notifyAll();
            }
        }
    }

    public Connection fetchConnection(long mills) throws InterruptedException {
        synchronized (pool) {
            // 完全超时
            if (mills < 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            } else {
                // 将要放弃连接的时间点
                long future = System.currentTimeMillis() + mills;
                // 尝试连接的duration
                long remaining = mills;
                // 两个判断 1连接池是否为空 2是否超过尝试连接时间 不满足其中任何条件退出循环
                while (pool.isEmpty() && remaining > 0) {
                    // 等待
                    pool.wait(remaining);
                    // 重新计算尝试连接的duration
                    remaining = future - System.currentTimeMillis();
                }
                // 返回connection
                Connection connection = null;
                if (!pool.isEmpty()) {
                    connection = pool.removeFirst();
                }
                return connection;
            }
        }
    }

}
